package com.qf.factory;
/*
@author fu
@date 2022/3/2119:32
自定义的工厂类
*/

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class BeanFactory {

    //构造方法私有化
    private BeanFactory(){};

    /*public static Object getBean(String beanName) throws Exception {

        //读取resource类路径下的资源文件bean.properties
        InputStream inputStream = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");

        //创建属性集合列表
        Properties prop = new Properties();

        //将资源文件所在的输入流加载属性集合列表中
        prop.load(inputStream);

        //通过key获取value
        String userService = prop.getProperty("userService");
        System.out.println(userService);
        //反射
        Class clazz = Class.forName(userService);
        //创建当前类实例
        Object obj = clazz.newInstance();
        return  obj ;
    }*/


    /*
    * 解析xml文件:dom4j: dom for Java 基于面向对象的解析xml文件的方式
    * */

    public static Object getBean(String id) throws Exception{

        //读取xml文件获取根标签对象
        //创建解析器
        SAXReader saxReader = new SAXReader();
        //读取路径下的配置文件bean.xml
        InputStream inputStream = BeanFactory.class.getClassLoader().getResourceAsStream("bean.xml");
        Document document = saxReader.read(inputStream) ;

        //定位到bean标签对象
        Element beanElement = (Element) document.selectSingleNode("//bean[@id='"+id+"']"); //id就是等会传递userService
        //通过标签对象获取class属性值的内容
        String userServiceImplClass = beanElement.attributeValue("class");
        //反射
        Class clazz = Class.forName(userServiceImplClass);
        Object obj = clazz.newInstance();
        return obj;


    }
}
